image

How to Inherit base class by super class in PHP ?

To inherit a base class by super class in PHP, you use the extends keyword. For example, the following code shows how to inherit the Animal class by the Dog class: PHP

class Animal {
    protected $name;

    public function __construct($name) {
        $this-name = $name;
    }

    public function getName() {
        return $this-name;
    }
}

class Dog extends Animal {
    public function bark() {
        echo Woof!;
    }
}
Use code with caution.andnbsp;Learn more content_copy The Dog class now inherits all of the properties and methods of the Animal class. This means that a Dog object can access the name property and call the getName() method of the Animal class. In addition, the Dog class can also override any of the properties and methods of the Animal class. For example, the following code shows how to override the getName() method of the Animal class to return a different value: PHP
class Dog extends Animal {
    public function getName() {
        return My dogand#39;s name is  . $this-name;
    }
}
Use code with caution.andnbsp;Learn more content_copy Now, when a Dog object calls the getName() method, it will return the string My dogand#39;s name is followed by the name of the dog. Inheritance is a powerful feature of PHP that allows you to reuse code and create more complex and specialized classes. Here are some additional things to keep in mind about inheritance in PHP:
  • Only public and protected properties and methods are inherited by subclasses. Private properties and methods are not inherited.
  • A subclass can override any public or protected property or method of its parent class.
  • A subclass cannot override a private property or method of its parent class.
  • A subclass can extend another subclass.